using MediatR;
using Microsoft.Extensions.Logging;
using RBAC.Domain.Dto.Output;
using RBAC.Domain.MaterialManage;
using RBAC.Domain.SalesManage;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Read.Api.Application.Command.ERP.SalesManagement;

namespace RBAC.Read.Api.Application.Handler.ERP.SalesManagement
{
    /// <summary>
    /// 无条件查询销售订单明细列表（只读）
    /// </summary>
    public class GetSalesOrderDetailItemsHandler : IRequestHandler<GetSalesOrderDetailItemsCommand, APIResult<List<SalesOrderDetailItemDto>>>
    {
        private readonly IBaseRepository<SalesOrderDetail> _detailRepo;
        private readonly IBaseRepository<Mater> _materRepo;
        private readonly ILogger<GetSalesOrderDetailItemsHandler> _logger;

        public GetSalesOrderDetailItemsHandler(
            IBaseRepository<SalesOrderDetail> detailRepo,
            IBaseRepository<Mater> materRepo,
            ILogger<GetSalesOrderDetailItemsHandler> logger)
        {
            _detailRepo = detailRepo;
            _materRepo = materRepo;
            _logger = logger;
        }

        public Task<APIResult<List<SalesOrderDetailItemDto>>> Handle(GetSalesOrderDetailItemsCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<List<SalesOrderDetailItemDto>>();
            try
            {
                _logger.LogInformation("开始无条件查询销售订单明细列表");

                // 查询所有未删除的明细
                var details = _detailRepo.GetAll("IsDeleted = 0", null);

                var dtoList = new List<SalesOrderDetailItemDto>();
                if (details.Any())
                {
                    var materIds = details.Select(x => x.MaterId).Distinct().ToList();
                    if (materIds.Any())
                    {
                        var inClause = string.Join(",", materIds.Select((_, i) => $"@Id{i}"));
                        var parameters = materIds.Select((id, i) => new { Key = $"@Id{i}", Value = (object)id })
                                                 .ToDictionary(x => x.Key, x => x.Value);
                        var materDict = _materRepo.GetAll($"Id IN ({inClause})", parameters)
                                                  .ToDictionary(m => m.Id);

                        int serial = 1;
                        foreach (var d in details)
                        {
                            materDict.TryGetValue(d.MaterId, out var m);
                            dtoList.Add(new SalesOrderDetailItemDto
                            {
                                Id = d.Id,
                                SerialNo = serial++,
                                MaterId = d.MaterId,
                                MaterCode = m?.MaterCode,
                                MaterName = m?.MaterName,
                                ModelSpec = m?.ModelSpec,
                                Unit = m?.Unit,
                                Num = d.Num,
                                Price = d.Price,
                                Amount = d.Num.HasValue && d.Price.HasValue ? d.Num.Value * d.Price.Value : 0,
                                Remark = d.Remark,
                                CreateTime = d.CreateTime,
                                CreateUser = d.CreateUser
                            });
                        }
                    }
                }

                result.Code = APIEnums.Success;
                result.Data = dtoList;
                result.Msg = "查询成功";
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "无条件查询销售订单明细失败：{Message}", ex.Message);
                result.Code = APIEnums.Error;
                result.Msg = "查询失败";
                result.Data = new List<SalesOrderDetailItemDto>();
            }

            return Task.FromResult(result);
        }
    }
}
